# coding:utf-8
import MySQLdb


def getresult(sql, param, database):
    try:
        conn = getconn(database=database)
        cursor = conn.cursor()
        cursor.execute(sql, param)
        results = cursor.fetchall()
        conn.commit()
        conn.close()
        return results
    except Exception, e:
        print 'error:'+e.message


def getresult_lazy(sql, param, database):
    try:
        conn = getconn(database=database)
        cursor = conn.cursor(cursorclass=MySQLdb.cursors.SSCursor)
        cursor.execute(sql, param)
        return cursor
        # results = cursor.fetchall()
        # conn.commit()
        # conn.close()
        # return results
    except Exception, e:
        print 'error'
        # print e.message
        # getresult_lazy(sql, param, database)


def getconn(database):
    try:
        conn = MySQLdb.connect(host=database[0], port=database[1], user=database[2], passwd=database[3], db=database[4],
                               charset='utf8')
        return conn
    except Exception, e:
        print 'error'
        # print e.message
        # getconn(database)


def getcommit(conn):
    try:
        conn.commit()
        conn.close()
    except Exception, e:
        print 'error'
        # print e.message
        # getcommit(conn)


def executesql(sql, param, database):
    try:
        conn = getconn(database=database)
        conn.cursor().execute(sql, param)
        conn.commit()
        conn.close()
    except Exception, e:
        print 'error'
        print e


def execute_many(sql, param, database):
    try:
        conn = getconn(database=database)
        cursor = conn.cursor()
        cursor.executemany(sql, param)
        getcommit(conn)
    except Exception, e:
        print 'mysql error', e
